	package com.pactera.mavenweb.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.pactera.mavenweb.core.exception.BusinessException;
import com.pactera.mavenweb.core.exception.ParameterException;
import com.pactera.mavenweb.entity.User;
import com.pactera.mavenweb.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	protected static Logger logger = Logger.getLogger(UserController.class);
	
	@Resource(name="userService")
	private UserService userService;
	
	@RequestMapping("/getAllUser")
	public String getAllUser(HttpServletRequest request) {
		request.setAttribute("userList", userService.getAllUser());
		logger.debug("debug: try debug log");
		
		return "/Index";
	}
	
	// use Native type for input parameter
	@RequestMapping("/getUser")
	public String getUser(String id,HttpServletRequest request) {
		request.setAttribute("user", userService.getUser(Integer.valueOf(id)));
		return "/editUser";
	}
	
	@RequestMapping("/toAddUser")
	public String toAddUser() throws Exception {
		
//		if(true) {
//			throw new BusinessException("10", "controller10");
//		}
		
		return "/addUser";
	}
	
	// use Object class for input parameter
	@RequestMapping("/addUser")
	public String addUser(User user,HttpServletRequest request) {
		
		// Mock data starting
		user.setSalt("12");
		// Mock data end
		
		userService.addUserSimpleRoles(user);
		
		return "redirect:/user/getAllUser";
	}
	
	// Use HttpServletResponse for Ajax
	@RequestMapping("/delUser")
	public void delUser(int id,HttpServletResponse response) {
		String result = "{\"result\":\"error\"}";
		if(userService.delUser(id)){
			result = "{\"result\":\"success\"}";
		}
		response.setContentType("application/json");
		
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/updateUser")  
	public String updateUser(User user,HttpServletRequest request) throws ParameterException {
		
		userService.updateUser(user);
		// we won't need these 2 lines
		user = userService.getUser(user.getId());
		request.setAttribute("user", user);
		return "redirect:/user/getAllUser";
	}
} 